package com.econvent.common.conn;

import com.alibaba.druid.pool.DruidDataSource;
import com.econvent.common.conn.config.BaseConfig;
import com.econvent.common.conn.config.Dbcp2Config;
import com.econvent.common.conn.entity.BaseDataSourceProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import java.util.Map;

@Slf4j
public class Dbcp2DataSourceBuilder extends DataSourceBuilder {
    @Override
    public void buildDataSource(BaseDataSourceProperty baseDataSourceProperty) {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUsername(baseDataSourceProperty.getUser());
        dataSource.setPassword(baseDataSourceProperty.getPassword());
        dataSource.setUrl(baseDataSourceProperty.getUrl());

        String driverClassName = baseDataSourceProperty.getDriverName();
        dataSource.setDriverClassName(driverClassName);

        this.dataSource = dataSource ;
    }

    @Override
    public void buildDataSourceConfig(BaseConfig dataSourceConfig) {
        Dbcp2Config dbcp2Config = (Dbcp2Config)dataSourceConfig ;

        try {
            Map configDescib = BeanUtils.describe(dbcp2Config);
            configDescib.forEach((propName, propValue) -> {
                if(null == propValue) {
                    return ;
                }

                try {
                    BeanUtils.setProperty((DruidDataSource)dataSource, (String) propName, propValue);
                } catch (Exception e) {
                    log.error("Dbcp2DataSourceBuilder setProperty error , propName is {}, propValue is {} " , propName, propValue);
                }
            });
        } catch (Exception e) {
            log.error("Dbcp2DataSourceBuilder buildDataSourceConfig error , the error is {} " , e);
        }
    }
}
